#!/usr/bin/env python3
"""
安全的音频处理器
解决大文件导致的段错误和内存泄漏问题
"""

import os
import sys
import gc
import warnings
from pathlib import Path
import logging
import subprocess

try:
    import soundfile as sf
    import numpy as np
except ImportError:
    print("安装依赖: pip install soundfile numpy")
    sys.exit(1)

# 禁用警告
warnings.filterwarnings("ignore", category=UserWarning)

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class SafeAudioProcessor:
    """安全的音频处理器，支持大文件分段处理"""
    
    def __init__(self, input_file, chunk_duration=300):  # 5分钟一段
        self.input_file = Path(input_file)
        self.chunk_duration = chunk_duration  # 秒
        self.temp_dir = Path("dialogue_process/temp_chunks")
        self.temp_dir.mkdir(exist_ok=True)
        
    def get_audio_duration(self):
        """获取音频时长"""
        try:
            result = subprocess.run([
                'ffprobe', '-v', 'error', '-show_entries', 
                'format=duration', '-of', 'default=noprint_wrappers=1:nokey=1',
                str(self.input_file)
            ], capture_output=True, text=True)
            return float(result.stdout.strip())
        except:
            # 回退方案
            import wave
            with wave.open(str(self.input_file), 'rb') as wav_file:
                frames = wav_file.getnframes()
                rate = wav_file.getframerate()
                return frames / float(rate)
    
    def split_audio(self):
        """将大音频文件分割成小片段"""
        try:
            duration = self.get_audio_duration()
            logger.info(f"音频总时长: {duration:.2f}秒")
            
            chunks = []
            start = 0
            chunk_index = 0
            
            while start < duration:
                end = min(start + self.chunk_duration, duration)
                chunk_file = self.temp_dir / f"chunk_{chunk_index:03d}.wav"
                
                # 使用ffmpeg分割音频
                cmd = [
                    'ffmpeg', '-i', str(self.input_file),
                    '-ss', str(start), '-t', str(end - start),
                    '-c', 'copy', str(chunk_file),
                    '-y', '-loglevel', 'error'
                ]
                
                subprocess.run(cmd, check=True)
                chunks.append(chunk_file)
                
                logger.info(f"创建片段 {chunk_index}: {start}-{end}秒")
                start = end
                chunk_index += 1
                
            return chunks
            
        except Exception as e:
            logger.error(f"音频分割失败: {e}")
            return []
    
    def cleanup(self):
        """清理临时文件"""
        for file in self.temp_dir.glob("chunk_*.wav"):
            try:
                file.unlink()
            except:
                pass
        try:
            self.temp_dir.rmdir()
        except:
            pass

def check_dependencies():
    """检查必要的依赖"""
    dependencies = {
        'ffmpeg': ['ffmpeg', '-version'],
        'ffprobe': ['ffprobe', '-version']
    }
    
    for name, cmd in dependencies.items():
        try:
            subprocess.run(cmd, capture_output=True, check=True)
            logger.info(f"✅ {name} 已安装")
        except (subprocess.CalledProcessError, FileNotFoundError):
            logger.error(f"❌ {name} 未安装，请运行: brew install ffmpeg")
            return False
    return True

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("使用方法: python audio_processor_safe.py <音频文件>")
        sys.exit(1)
    
    audio_file = sys.argv[1]
    
    if not check_dependencies():
        sys.exit(1)
    
    processor = SafeAudioProcessor(audio_file)
    
    try:
        chunks = processor.split_audio()
        if chunks:
            print(f"✅ 成功分割为 {len(chunks)} 个片段")
            print("片段文件:")
            for chunk in chunks:
                print(f"  - {chunk}")
        else:
            print("❌ 分割失败")
    finally:
        pass  # 临时文件会保留用于后续处理